import 'dart:io';
import 'dart:async';
import 'dart:typed_data';
// import 'package:bj_car/widgets/my_app_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:magic_car/res/colors.dart';
import 'package:magic_car/util/HttpHelper.dart';

import 'package:orientation/orientation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:ui' as ui show ImageByteFormat, Image;

import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:image_pickers/image_pickers.dart';
///
/// Description: 签名画板并截图
///
class DrawingBoardPage extends StatefulWidget {
  @override
  _DrawingBoardPageState createState() => _DrawingBoardPageState();
}

class _DrawingBoardPageState extends State<DrawingBoardPage> {
  /// 标记签名画板的Key，用于截图
  GlobalKey _globalKey;

  /// 已描绘的点
  List<Offset> _points = <Offset>[];

  /// 记录截图的本地保存路径
  String _imageLocalPath;

  File signFile;

  @override
  void initState() {
    super.initState();
    // Init
    _globalKey = GlobalKey();
  }

  @override
  void dispose() {
    super.dispose();
    // 强制竖屏
    // SystemChrome.setPreferredOrientations([
    //   DeviceOrientation.portraitUp,
    //   DeviceOrientation.portraitDown
    // ]);
    OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
  }

  @override
  Widget build(BuildContext context) {
    OrientationPlugin.forceOrientation(DeviceOrientation.landscapeLeft);

    return
        // RotatedBox(quarterTurns: 1,child:
        Scaffold(
      // appBar: MyAppBar(title:"签名"),
      appBar: AppBar(title: Text('协议'),backgroundColor: Colors.white,),
      body: Container(
        // margin: EdgeInsets.fromLTRB(16.0, 12.0, 16.0, 0.0),
        child: Column(
          children: <Widget>[
            Expanded(
                child: RepaintBoundary(
              key: _globalKey,
              child: Container(
                // height: 180.0,
                decoration: BoxDecoration(
                  color: Colours.base_page_color,
                  border: Border.all(color: Colors.grey, width: 0.5),
                ),
                //  child:

                // Text('签名')
                child: Stack(
                  children: [
                    // Container(
                    //     child: Image.asset(
                    //         "resource/images/user/authinspect.jpeg")),
                    GestureDetector(
                      onPanUpdate: (details) => _addPoint(details),
                      onPanEnd: (details) => _points.add(null),
                    ),
                    CustomPaint(
                      painter: BoardPainter(_points),
                    ),
                  ],
                ),
              ),
            )),
            Row(
              children: <Widget>[
                RaisedButton(
                  color: Colours.bj_green_g1,
                  onPressed: () async {
                    setState(() {
                      _points?.clear();
                      _points = [];
                      _imageLocalPath = null;
                    });
                  },
                  child: Text(
                    '清空',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
                Expanded(child: Container()),
                RaisedButton(
                  color: Colours.bj_orange_o1,
                  onPressed: () async {
                    // File toFile = await _saveImageToFile();
                    // String toPath = await _capturePng(toFile);
                    // print('Signature Image Path: $toPath');
                    // setState(() {
                    //   _imageLocalPath = toPath;
                    //   signFile = toFile;
                    // });
                    // uploadsignpic();
                    _savepic();
                  },
                  child: Text(
                    '确认签名',
                    style: TextStyle(
                      fontSize: 14.0,
                      color: Colors.white,
                      fontWeight: FontWeight.normal,
                    ),
                  ),
                ),
              ],
            ),
            // Container(
            //   alignment: Alignment.centerLeft,
            //   margin: EdgeInsets.only(top: 4.0),
            //   child: Text('Image local path:'),
            // ),
            // Container(
            //   alignment: Alignment.centerLeft,
            //   margin: EdgeInsets.only(top: 4.0),
            //   child: Text(
            //     _imageLocalPath ?? '',
            //     style: TextStyle(color: Colors.blue),
            //   ),
            // ),
            // Container(
            //   alignment: Alignment.centerLeft,
            //   margin: EdgeInsets.only(top: 4.0),
            //   child: Text('Show Image: '),
            // ),
            // Container(
            //   height: 180.0,
            //   margin: EdgeInsets.only(top: 4.0),
            //   alignment: Alignment.center,
            //   decoration: BoxDecoration(
            //     border: Border.all(color: Colors.grey, width: 0.5),
            //   ),
            //   child: Image.file(File(_imageLocalPath ?? '')),
            // )
          ],
        ),
      ),
      // )
    );
  }

  //上传签名图片
  uploadsignpic() async {
    //  File _files = await FlutterNativeImage.compressImage(_imageLocalPath);

    Map<String, String> map = new Map();

    HttpHelper.upLoadSignImage(_imageLocalPath, (data) {
      //loadpage.close();
      print(data);
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        updateqianming(data);
      }
    }, params: map);
  }

  //更新用户签名
  //qianming
  updateqianming(datamap) async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    Map<String, String> map = new Map();
    map["id"] = pref.getString('uid').toString();
    map['qianming'] = datamap["attachment"];

    HttpHelper.post(HttpHelper.API_UpdateAvatar, (data) async {
      if (data != null) {
        print(data);
        if(data["code"]==1){
          sign();
        }
       // Toast.show(data["msg"], context);
      }
    }, params: map);
  }

  //签名
  sign() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    Map<String, String> map = new Map();
    map["id"] = pref.getString('uid').toString();
    

    HttpHelper.post(HttpHelper.API_Sign_inline, (data) async {
      if (data != null) {
        print(data);
        Toast.show(data["info"], context);
        Navigator.of(context).pop(1);
      }
    }, params: map);
  }

  /// 添加点，注意不要超过Widget范围
  _addPoint(DragUpdateDetails details) {
    RenderBox referenceBox = _globalKey.currentContext.findRenderObject();
    Offset localPosition = referenceBox.globalToLocal(details.globalPosition);
    double maxW = referenceBox.size.width;
    double maxH = referenceBox.size.height;
    // 校验范围
    if (localPosition.dx <= 0 || localPosition.dy <= 0) return;
    if (localPosition.dx > maxW || localPosition.dy > maxH) return;
    setState(() {
      _points = List.from(_points)..add(localPosition);
    });
  }

  /// 选取保存文件的路径
  Future<File> _saveImageToFile() async {
    Directory tempDir = await getTemporaryDirectory();
    int curT = DateTime.now().millisecondsSinceEpoch;
    String toFilePath = '${tempDir.path}/$curT.png';
    File toFile = File(toFilePath);
    bool exists = await toFile.exists();
    if (!exists) {
      await toFile.create(recursive: true);
    }
    return toFile;
  }

  //保存图片
  _savepic() async {
    BuildContext buildContext = _globalKey.currentContext;
    if (null != buildContext) {
      RenderRepaintBoundary boundary = buildContext.findRenderObject();
      ui.Image image = await boundary.toImage();
      ByteData byteData =
          await image.toByteData(format: ui.ImageByteFormat.png);
     if (Platform.isAndroid) {

      if(await Permission.storage.request().isGranted) {
     
       final result =
          await ImageGallerySaver.saveImage(byteData.buffer.asUint8List());
            String res1 = result['filePath'];
      String path = res1.replaceAll("file://", '');
      setState(() {
        _imageLocalPath = path;
      });
    }
     
    } else {
       if(await Permission.photos.request().isGranted) {
        String imagepath = await ImagePickers.saveByteDataImageToGallery(byteData.buffer.asUint8List());
            setState(() {
              _imageLocalPath = imagepath;
            });
      //  final result =
      //     await ImageGallerySaver.saveImage(byteData.buffer.asUint8List());
      //       String res1 = result['filePath'];
      // String path = res1.replaceAll("file://", '');
      // setState(() {
      //   _imageLocalPath = path;
      // });
    }
    }
    // BuildContext buildContext = _globalKey.currentContext;
    // if (null != buildContext) {
    //   RenderRepaintBoundary boundary = buildContext.findRenderObject();
    //   ui.Image image = await boundary.toImage();
    //   ByteData byteData =
    //       await image.toByteData(format: ui.ImageByteFormat.png);
    //   final result =
    //       await ImageGallerySaver.saveImage(byteData.buffer.asUint8List());
    //   String res1 = result['filePath'];
    //   String path = res1.replaceAll("file://", '');
    //   setState(() {
    //     _imageLocalPath = path;
    //   });
      uploadsignpic();
     }
    //  RenderRepaintBoundary boundary =
    //     _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    // var image = await boundary.toImage(pixelRatio: 3.0);
    // ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
    // _postBytes = byteData?.buffer.asUint8List();
    // //保存到相册
    // var result = await ImageGallerySaver.saveImage(_postBytes!);
    // String path = result['filePath'].replaceAll("file://", '');
  }

  /// 截图，并且返回图片的缓存地址
  Future<String> _capturePng(File toFile) async {
    // 1. 获取 RenderRepaintBoundary
    RenderRepaintBoundary boundary =
        _globalKey.currentContext.findRenderObject();
    // 2. 生成 Image
    ui.Image image = await boundary.toImage();
    // 3. 生成 Uint8List
    ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData.buffer.asUint8List();
    // 4. 本地存储Image
    // toFile.writeAsBytes(pngBytes);
    // return toFile.path;
    var result = await ImageGallerySaver.saveImage(pngBytes);
    //String path = result['filePath'].replaceAll("file://", '');
    String res1 = result['filePath'];
    String path = res1.replaceAll("file://", '');
    return path;
  }
}

class BoardPainter extends CustomPainter {
  BoardPainter(this.points);

  final List<Offset> points;

  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = Colors.black
      ..strokeCap = StrokeCap.round
      ..strokeWidth = 5.0;
    for (int i = 0; i < points.length - 1; i++) {
      if (points[i] != null && points[i + 1] != null) {
        canvas.drawLine(points[i], points[i + 1], paint);
      }
    }
  }

  bool shouldRepaint(BoardPainter other) => other.points != points;
}
